package maldade.persistence.dao;

import java.lang.reflect.ParameterizedType;

import maldade.persistence.service.PersistenceServiceFactory;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

/**
 * All DAO's must derive this.
 * 
 * @author rNojiri
 *
 * @param <T>
 */
public abstract class AbstractDAO<T>
{
	private Class<T> persistentClass;

	private Session session;

	/**
	 * Initialized the session.
	 */
	@SuppressWarnings("unchecked")
	public AbstractDAO()
	{
		session = PersistenceServiceFactory.getPersistenceService()
				.getSession();
		
		persistentClass = (Class< T >) ( (ParameterizedType) getClass().getGenericSuperclass() )
        .getActualTypeArguments()[ 0 ];
	}

	/**
	 * Returns the named query.
	 * 
	 * @param name
	 * @return
	 */
	protected Query getQueryByName(String name)
	{
		String fullName = persistentClass.getName() + "." + name;

		return session.getNamedQuery(fullName);
	}

	/**
	 * Creates a new Criteria.
	 * 
	 * @return Criteria
	 */
	protected Criteria createCriteria()
	{
		return session.createCriteria(persistentClass);
	}
	
	/**
	 * Saves or update the object on database.
	 * 
	 * @param entity
	 */
	public void saveOrUpdate(T entity)
	{
		session.saveOrUpdate(entity);
	}
	
	/**
	 * Deletes the object from database.
	 * 
	 * @param entity
	 */
	public void delete(T entity)
	{
		session.delete(entity);
	}
	
	/**
	 * Creates a native SQL query.
	 */
	public SQLQuery createNativeQuery(String query)
	{
		return session.createSQLQuery(query);
	}
}
